import 'dart:convert';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:get_storage/get_storage.dart';
import 'package:jxchmz/%E9%94%80%E5%94%AE/%E4%BC%9A%E5%91%98%E7%99%BB%E8%AE%B0/VipAdd.dart';
import 'package:jxchmz/%E9%94%80%E5%94%AE/%E4%BC%9A%E5%91%98%E7%99%BB%E8%AE%B0/VipUpdate.dart';
import 'package:jxchmz/API/%E9%94%80%E5%94%AE%E7%AE%A1%E7%90%86/vipManage.dart';
import 'package:jxchmz/Getx%E5%B7%A5%E5%85%B7/GetxTools.dart';
import 'package:jxchmz/Getx%E5%B7%A5%E5%85%B7/KSProgressDialog.dart';

class VipList extends StatefulWidget {
  @override
  _VipListState createState() => new _VipListState();
}

class _VipListState extends State<VipList> {
  TextEditingController SearchController = new TextEditingController();

//会员列表
  List VipList = [];

  // 当前页数
  int _page = 1;

  // 是否还有
  bool _hasMore = true;

  // 滚动控制器
  ScrollController _scrollController = new ScrollController();

//页面加载完成时
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    // 监听滚动事件
    _scrollController.addListener(() {
      var maxScroll = _scrollController.position.maxScrollExtent;
      var pixel = _scrollController.position.pixels;
      if (maxScroll == pixel) {
        if (_hasMore) {
          _page++;
          GetlistVip();
        }
      }
    });

    Future.delayed(Duration.zero, () {
      GetlistVip();
    });
  }

  ///页面卸载
  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
  }

  ///当 State 被暂时从视图树中移除时，会调用这个方法，同时页面切换时，也会调用。
  @override
  void deactivate() {
    // TODO: implement dispose
    super.deactivate();
  }

  ///在 initState() 之后调用，当 State 对象的依赖关系发生变化时，该方法被调用，初始化时也会调用。
  @override
  void didChangeDependencies() {
    // TODO: implement didChangeDependencies
    super.didChangeDependencies();
  }

  // TODO: add state variables and methods
  @override
  Widget build(BuildContext context) {
    // TODO: add widget build method
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: AppBar(
        backgroundColor: Colors.white,
        title: CupertinoSearchTextField(
          controller: SearchController,
          placeholder: "Enterthemembernametosearch".tr,
          placeholderStyle: TextStyle(fontSize: 13, color: Colors.black38),
        ),
        centerTitle: true,
        elevation: 0,
        iconTheme: IconThemeData(color: Colors.black),
        actions: [
          TextButton(
              onPressed: () {
                //搜索事件
                SearchOrder();
              },
              child: Text(
                "Search".tr,
                style: TextStyle(color: Colors.black),
              ))
        ],
      ),
      body: Container(
        child: ListView.separated(
            itemBuilder: (context, index) {
              return ListTile(
                title: Column(
                  children: [
                    Row(
                      children: [
                        Container(
                          child: Text(
                            "name".tr+":${VipList[index]['name']}",
                            style: TextStyle(fontSize: 13),
                          ),
                        ),
                        Container(
                          child: Text("Cardopeningdate".tr+":${VipList[index]['openCardDate']}", style: TextStyle(fontSize: 13, color: Colors.black38)),
                        ),
                      ],
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    ),
                    Container(
                      height: 5,
                    ),
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        Container(
                          child: Text(
                              "gender".tr+":${VipList[index]['sex'] == 1 ? "man".tr : VipList[index]['sex'] == 2 ? "woman".tr : "secrecy".tr}",
                              style: TextStyle(fontSize: 13)),
                        ),
                        Container(
                          child: Text("Mobilephonenumber".tr+":${VipList[index]['phone']}", style: TextStyle(fontSize: 13)),
                        )
                      ],
                    ),
                    Container(
                      height: 5,
                    ),
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        Container(
                          child: Text("IDnumber".tr+":${VipList[index]['idCard']}", style: TextStyle(fontSize: 13)),
                        ),
                        Container(
                          child: Text("Membershipcardnumber".tr+":${VipList[index]['vipCardNumber']}", style: TextStyle(fontSize: 13)),
                        )
                      ],
                    ),
                    Container(
                      height:10,
                    ),
                    Row(
                      mainAxisAlignment: MainAxisAlignment.end,
                      children: [
                        Container(
                          child: MaterialButton(
                            shape: const RoundedRectangleBorder(
                              //边框圆角
                              borderRadius: BorderRadius.all(
                                Radius.circular(15),
                              ),
                            ),
                            child: Text(
                              "revise".tr,
                              style: TextStyle(color: Colors.white, fontSize: 13),
                            ),
                            onPressed: () {
                              //进入详情
                              Get.to(VipUpdate(),arguments: {"Vip":VipList[index]});
                            },
                            color: Colors.orange,
                          ),
                          width: 80,
                          height: 30,
                          alignment: Alignment.centerRight,
                        ),
                        Container(
                          width: 5,
                        ),
                        Container(
                          child: MaterialButton(
                            shape: const RoundedRectangleBorder(
                              //边框圆角
                              borderRadius: BorderRadius.all(
                                Radius.circular(15),
                              ),
                            ),
                            child: Text(
                              "Delete".tr,
                              style: TextStyle(color: Colors.white, fontSize: 13),
                            ),
                            onPressed: () {
                              Get.defaultDialog(
                                  title: "prompt".tr,
                                  middleText: "Areyousureyouwanttoremovethismember".tr,
                                  barrierDismissible: false,
                                  confirm: MaterialButton(
                                    onPressed: () async {
                                      Get.back();
                                       VipDelete(VipList[index]['id']);
                                    },
                                    child: Text("sure".tr,style: TextStyle(color: Colors.white),),
                                    color: Color(0xff372D9F),
                                  ),
                                  cancel: MaterialButton(
                                    onPressed: () {
                                      Get.back();
                                    },
                                    child: Text(
                                      "Cancel".tr,
                                      style: TextStyle(color: Color(0xff372D9F)),
                                    ),
                                    color: Colors.white,
                                    //边框样式
                                    shape: const RoundedRectangleBorder(
                                      //边框颜色
                                      side: BorderSide(
                                        color: Color(0xff372D9F),
                                        width: 1,
                                      ),
                                    ),
                                  ));

                            },
                            color: Colors.red,
                          ),
                          width: 80,
                          height: 30,
                          alignment: Alignment.centerRight,
                        ),
                      ],
                    )
                  ],
                ),
              );
            },
            separatorBuilder: (context, index) {
              return Divider();
            },
            itemCount: VipList.length),
      ),
      floatingActionButton: FloatingActionButton(
        child: Icon(Icons.add),
        onPressed: () {
          //添加会员
          Get.to(VipAdd())!.then((value){
            SearchOrder();
          });
        },
      ),
    );
  }

  //搜索事件
  SearchOrder() {
    _page = 1;
    _hasMore = true;
    VipList = [];
    GetlistVip();
  }

  //获取会员列表
  GetlistVip() async {
    //取出本地个人信息
    GetStorage getStorage = new GetStorage();
    var Userid = json.decode(getStorage.read("User"))['user']['userId'];
    //搜索参数
    var data = {"pageNum": _page, "pageSize": 10, "reasonable": false, "name": SearchController.text,"operator":Userid};
    var ResponseData = await VipManage().GetVipList(data);
    if (ResponseData['code'] == 200) {
      var List = ResponseData['rows'];
      if (List.length <= 0) {
        // 关闭加载
        this._hasMore = false;
      } else {
        List.forEach((element) {
          VipList.add(element);
        });
      }
    } else {
      new GetxTools().ErrorToast("Memberlistacquisitionfailed".tr);
    }
    setState(() {});
  }
  //删除会员
  VipDelete(id) async {
    //取出本地个人信息
    GetStorage getStorage = new GetStorage();
    KSProgressDialog().LoadingToast("Delete".tr, context);
    var ResponseData = await VipManage().DeleteVip(id);
    KSProgressDialog().CloseLoading();
    if (ResponseData['code'] == 200) {
     GetxTools().SuccessToast("Thedeletionwassuccessful".tr);
     SearchOrder();
    } else {
      new GetxTools().ErrorToast("Memberdeletionfailed".tr);
    }
    setState(() {});
  }
}
